import dayjs from 'dayjs'
import { DatePicker, GetProps } from 'antd'
import type { ICellRendererParams } from '@ag-grid-community/core'

import styles from './styles.module.less'

type TDatePickerProps = GetProps<typeof DatePicker>

interface IDateCellRendererProps extends ICellRendererParams<any, string> {
  datePickerProps?: Omit<TDatePickerProps, 'value' | 'onChange' | 'disabled' | 'picker'>
}

export const DateCellRenderer = Object.assign(
  ({ value, node, column, colDef, data, datePickerProps }: IDateCellRendererProps) => {
    // 计算是否可编辑（用于禁用控制），兼容 editable 为布尔或函数
    const isEditable = (() => {
      const editable = colDef?.editable as any
      try {
        if (typeof editable === 'function') {
          return !!editable({ data, node, colDef })
        }
        return !!editable
      } catch {
        return !!editable
      }
    })()

    let dateValue
    if (typeof value === 'string' && value.trim()) {
      const date = dayjs(value.trim())
      if (date.isValid()) {
        dateValue = date
      }
    }

    return (
      <DatePicker
        allowClear={false}
        {...datePickerProps}
        className={styles.DateCellRenderer}
        value={dateValue as any}
        onChange={(_date, dateString) => {
          const val = typeof dateString === 'string' ? dateString || '' : ''
          const colId =
            column?.getColId?.() ?? (typeof (column as any)?.colId === 'string' ? (column as any).colId : undefined)
          if (colId && node) {
            node.setDataValue(colId, val)
          }
        }}
        picker="date"
        disabled={!isEditable}
      />
    )
  },
  {
    defineProps: (
      props: Pick<IDateCellRendererProps, 'datePickerProps'>,
    ): Pick<IDateCellRendererProps, 'datePickerProps'> => props,
  },
)
